//
//  orderDetailsViewController.m
//  QXDLLOrdersModule
//
//  Created by DL on 17/1/4.
//  Copyright © 2017年 DLL. All rights reserved.
//

#import "orderDetailsViewController.h"
#import "DLLApiManager.h"
#import <QXDriverConfiguration/QXDriverConfiguration.h>
#import <SDWebImage/UIImageView+WebCache.h>
#import "ongoingOrdersViewController.h"
#import "MapViewRoutePlan.h"
#import "UtilsMacros.h"
#import <MAMapKit/MAMapKit.h>
#import "LocationManager.h"
#import "UserLocationModel.h"
#import <AMapNaviKit/AMapNaviKit.h>
#import <AMapSearchKit/AMapSearchKit.h>
#import "HeaderMacro.h"
#import "ComplaintVC.h"
#import "carEndTheTripViewController.h"
#import "paymentOrderDetailsViewController.h"
#import "endTheTripViewController.h"
#import <QXDataManager/QXDataManager.h>
#import <AMapFoundationKit/AMapFoundationKit.h>
#import "MANaviRoute.h"
#import "CommonUtility.h"
#import <QXYueYueModels/QXYYUserDriverModel.h>
#import "AppManager.h"
#import "AppInfoModel.h"
#import <SDWebImage/SDImageCache.h>
#import "NotificationNameManager.h"
#import "SendLocationModel.h"
#import "SendLocationManager.h"
#import "OrderClosingManager.h"
#import <QXYueYueModels/QXYYOrderDetailModel.h>
#import <QXYueYueModels/QXYYUserPassengerModel.h>



#import <Mapbox/Mapbox.h>
#import <MapboxDirections/MapboxDirections-Swift.h>
#import "CustomMGLPointAnnotation.h"
#import "CustomMGLAnnotationView.h"
#import <MapboxDirections/MBRouteOptions.h>

#import "MapManager.h"

#import "CarImageManager.h"


@interface orderDetailsViewController ()<MAMapViewDelegate , AMapSearchDelegate , MGLMapViewDelegate>
/**
 底图
 */
@property (weak, nonatomic) IBOutlet UIView *backView;

/**
 底图的高度
 如果是接机状态高度235,如果不是205
 */
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *backViewHeight;


/**
 如何是接机状态15 , 如果不是-15
 */
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *marginToDividingLine;


/// 导航栏左侧按钮
@property (weak, nonatomic) IBOutlet UIBarButtonItem *leftBarButtonItem;
/// 头像
@property (weak, nonatomic) IBOutlet UIImageView *heardImageView;
/// 手机尾号
@property (weak, nonatomic) IBOutlet UILabel *phoneTailNumberLabel;
/// 拨打电话
@property (weak, nonatomic) IBOutlet UIButton *callPhoneButton;
/// 时间图片
@property (weak, nonatomic) IBOutlet UIImageView *timeImageView;
/// 时间
@property (weak, nonatomic) IBOutlet UILabel *timeLabel;
/// 类型
@property (weak, nonatomic) IBOutlet UILabel *statusLabel;
/// 订单状态
@property (weak, nonatomic) IBOutlet UILabel *typeLabel;
/// 起点图片
@property (weak, nonatomic) IBOutlet UIImageView *startImageView;
/// 终点图片
@property (weak, nonatomic) IBOutlet UIImageView *endImageView;
/// 起点位置
@property (weak, nonatomic) IBOutlet UILabel *startLabel;
/// 终点位置
@property (weak, nonatomic) IBOutlet UILabel *endLabel;
/// 接机图片
@property (weak, nonatomic) IBOutlet UIImageView *aircraftImageView;
@property (weak, nonatomic) IBOutlet UILabel *aircraftLabel;


/**
 去接乘客按钮
 */
@property (weak, nonatomic) IBOutlet UIButton *pickUpPassengerButton;


/**
 地图背景视图
 */
@property (weak, nonatomic) IBOutlet UIView *mapBackView;



/**
 乘客信息背景图的高度
 */
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *passengerInfoBackViewHeight;


/**
 信息背景视图的距离底部的距离
 如果订单已经被取消-75;
 */
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *infoBackViewMarignToBottom;

/// 订单状态码
@property(nonatomic , assign) OrderStatusEnumCode orderStatusEnumCode;

/// 是否收到乘客取消订单的推送
@property(nonatomic , assign) BOOL isReceivedTheNotificationThatPassengerHasCancelTheOrder;



#pragma mark - 地图信息
@property (weak, nonatomic) IBOutlet MAMapView *mapView;

/// 起点大头针
@property(nonatomic , strong) MAPointAnnotation *startAnnotation;

/// 终点大头针
@property(nonatomic , strong) MAPointAnnotation *destinationAnnotation;

/// 规划的路线对象
@property(nonatomic , strong) MANaviRoute *naviRoute;

/// 线路规划搜索对象
@property(nonatomic , strong) AMapSearchAPI *searchAPI;


/// 地图距离顶部的距离
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *mapViewToTop;

@property (nonatomic , strong) UIAlertController *alertVC;




/// mapbox 加载
@property(nonatomic , assign) BOOL isLoadFinished;
/// 当前的导航路线
@property(nonatomic , strong) MBRoute *currentMapBoxRoute;
/// 当前在地图上显示的路线
@property(nonatomic , strong) MGLPolyline *currentMapboxRouteLine;

/// 起点注释
@property(nonatomic , strong) CustomMGLPointAnnotation *orginPinMapbox;
/// 终点注释
@property(nonatomic , strong) CustomMGLPointAnnotation *destPinMapbox;
/// mapbox 地图
@property(nonatomic , strong) MGLMapView *mapboxMapView;


@end

@implementation orderDetailsViewController


+ (instancetype)shareSelf {
    return [[UIStoryboard storyboardWithName:@"Orders" bundle:nil] instantiateViewControllerWithIdentifier:@"orderDetailsViewController"];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self configureDefaultsAttributes];

}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    __weak typeof(self) weakSelf = self;
    
    [[OrderClosingManager shareManager] openNotificationWithOrderUuid:self.ordersDetailsModel.uuid receivedNotification:^(NSNotification *aNotification) {
        __strong typeof(self) strongSelf = weakSelf;
        
        [strongSelf.alertVC dismissViewControllerAnimated:YES completion:^{
            
        }];
        
    }];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    if ([MapManager shareManager].currentMapType == MapTypeMapBox) {
        
        if (self.isLoadFinished == NO) {
            [self initMapboxMapView];
            self.isLoadFinished = YES;
        }
    }else if ([MapManager shareManager].currentMapType == MapTypeGD) {
        
        if (self.isLoadFinished == NO) {
            
            [self configureMapView];
            self.isLoadFinished = YES;
        }
    }
}

#pragma mark - 配置 mapbox 的地图
- (void)initMapboxMapView {
    
    self.mapboxMapView = [[MGLMapView alloc] initWithFrame:CGRectMake(0, 0, self.mapBackView.frame.size.width, self.mapBackView.frame.size.height)];
    
    self.mapboxMapView.delegate = self;
    self.mapboxMapView.showsUserLocation = YES;
    self.mapboxMapView.userInteractionEnabled = NO;
    
    [self.mapboxMapView setUserTrackingMode:(MGLUserTrackingModeFollow) animated:YES];
    [self.mapBackView addSubview:self.mapboxMapView];
    
    self.mapboxMapView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    [self.mapboxMapView bringSubviewToFront:self.mapBackView];
    
    [self beginMapboxRouteLineConfigurations];
    
}

#pragma mapbox 开始 Mapbox 地图的路线规划配置
- (void)beginMapboxRouteLineConfigurations {
    
    if (self.mapboxMapView.userLocation.coordinate.latitude == 0 || self.mapboxMapView.userLocation.coordinate.longitude == 0) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            MBProgressHUD *mb = [MBProgressHUD showWithText:@"定位失败" onView:self.view hiddenDuration:2.0];
            mb.userInteractionEnabled = NO;
        });
        return;
    }
    
    CustomMGLPointAnnotation *orginPin = [[CustomMGLPointAnnotation alloc] init];
    orginPin.identifier = @"起点";
    orginPin.title = @"起点";
    orginPin.coordinate = CLLocationCoordinate2DMake(self.ordersDetailsModel.originLat, self.ordersDetailsModel.originLng);
    
    CustomMGLPointAnnotation *destPin = [[CustomMGLPointAnnotation alloc] init];
    destPin.identifier = @"终点";
    destPin.title = @"终点";
    destPin.coordinate = CLLocationCoordinate2DMake(self.ordersDetailsModel.destLat, self.ordersDetailsModel.destLng);
    
    
    NSArray<CustomMGLPointAnnotation *>* pinArr = @[orginPin , destPin];
    [self.mapboxMapView addAnnotations:pinArr];
    
    MBWaypoint *orginWaypoint = [[MBWaypoint alloc] initWithCoordinate:orginPin.coordinate coordinateAccuracy:(kCLLocationAccuracyBest) name:@"起点"];
    MBWaypoint *destWaypoint = [[MBWaypoint alloc] initWithCoordinate:destPin.coordinate coordinateAccuracy:(kCLLocationAccuracyBest) name:@"终点"];
    NSArray<MBWaypoint *>* waypoints = @[orginWaypoint , destWaypoint];
    [self mapBoxDrawRouteLinePass:waypoints];
    
}


/// 规划地图并展示地图
- (void)mapBoxDrawRouteLinePass:(NSArray <MBWaypoint *>*)wayPoints {
    
    if (wayPoints.count < 2) {
        
        return;
    }
    
    MBRouteOptions *options = [[MBRouteOptions alloc] initWithWaypoints:wayPoints profileIdentifier:(MBDirectionsProfileIdentifierAutomobileAvoidingTraffic)];
    options.includesSteps = true;
    
    MBDirections *directions = [MBDirections sharedDirections];
    
    
    __weak typeof(self) weakSelf = self;
    NSURLSessionDataTask *task = [directions calculateDirectionsWithOptions:options completionHandler:^(NSArray<MBWaypoint *> * _Nullable wayPoints, NSArray<MBRoute *> * _Nullable routes, NSError * _Nullable error) {
        
        __strong typeof(self) strongSelf = weakSelf;
        
        if (error) {
            
            return;
        }
        
        
        if (routes.count > 0) {
            
            MBRoute *route = routes.firstObject;
            
            if (route.coordinateCount > 0) {
                
                // Convert the route’s coordinates into a polyline.
                CLLocationCoordinate2D *routeCoordinates = malloc(route.coordinateCount * sizeof(CLLocationCoordinate2D));
                [route getCoordinates:routeCoordinates];
                MGLPolyline *routeLine = [MGLPolyline polylineWithCoordinates:routeCoordinates count:route.coordinateCount];
                
                [strongSelf.mapboxMapView addAnnotation:routeLine];
                [strongSelf.mapboxMapView setVisibleCoordinates:routeCoordinates count:route.coordinateCount edgePadding:UIEdgeInsetsMake(30, 30, 310, 30) animated:YES];
                free(routeCoordinates);
            }
        }
        
    }];
    [task resume];
}



#pragma mark - 配置地图属性
- (void)configureMapView {
    
    self.mapView.delegate = self;
    self.startAnnotation = [[MAPointAnnotation alloc] init];
    self.destinationAnnotation = [[MAPointAnnotation alloc] init];
    self.mapView.userInteractionEnabled = NO;
    self.mapView.showsUserLocation = NO;
    
    
    if (![LocationManager shareManager].userLocationModel) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            MBProgressHUD *mb = [MBProgressHUD showWithText:@"地图定位失败" onView:self.view hiddenDuration:2.0];
            mb.userInteractionEnabled = NO;
        });
        
    }else {
        
        // 如果订单已经取消那么不再规划路线,只显示起点,终点位置
        if (self.orderStatusEnumCode == OrderStatusEnumCode_NewStroke_PassengerCancel ||
            self.orderStatusEnumCode == OrderStatusEnumCode_PassengersCancel_StrokeDetemination_DriverNotArrive ||
            self.orderStatusEnumCode == OrderStatusEnumCode_PassengersCancel_StrokeDetemination_DriverArrived ||
            self.orderStatusEnumCode == OrderStatusEnumCode_NewStroke_DriverCancel ||
            self.orderStatusEnumCode == OrderStatusEnumCode_NoFare_StrokeDetermination_PassengersCancelOrder ||
            self.orderStatusEnumCode == OrderStatusEnumCode_NoFare_GotoPickUpPassengers_PassengersCancelOrder ||
            self.orderStatusEnumCode == OOrderStatusEnumCode_NoFare_WaitingForPassengers_PassengersCancelOrder ||
            self.orderStatusEnumCode == OrderStatusEnumCode_HaveFare_StrokeDetermination_PassengersCancelOrder ||
            self.orderStatusEnumCode == OrderStatusEnumCode_HaveFare_GotoPickUpPassengers_PassengersCancelOrder ||
            self.orderStatusEnumCode == OrderStatusEnumCode_HaveFare_WaitingForPassengers_PassengersCancelOrder ||
            self.orderStatusEnumCode == OrderStatusEnumCode_NoFare_StrokeDetermination_DriverCancelOrder ||
            self.orderStatusEnumCode == OrderStatusEnumCode_NoFare_WaitingForPassengers_DriverCancelOrder||
            self.orderStatusEnumCode == OrderStatusEnumCode_NoFare_GotoPickUpPassengers_DriverCancelOrder ||
            self.orderStatusEnumCode == OrderStatusEnumCode_HaveFare_StrokeDetermination_DriverCancelOrder ||
            self.orderStatusEnumCode == OrderStatusEnumCode_HaveFare_GotoPickUpPassengers_DriverCancelOrder ||
            self.orderStatusEnumCode == OrderStatusEnumCode_HaveFare_WaitingForPassengers_DriverCancelOrder ||
            self.orderStatusEnumCode == OrderStatusEnumCode_OrderClosedByCustomerService) {
            
            NSMutableArray *annotationArray = [NSMutableArray array];
            
            MAPointAnnotation *annotation_Origin = [[MAPointAnnotation alloc] init];
            annotation_Origin.title = @"起点";
            annotation_Origin.coordinate = CLLocationCoordinate2DMake(self.ordersDetailsModel.originLat, self.ordersDetailsModel.originLng);
            [annotationArray addObject:annotation_Origin];
            
            if (!([self.ordersDetailsModel.typeTime isEqualToString:@"3"] || [self.ordersDetailsModel.typeTime isEqualToString:@"4"])) {
                
                MAPointAnnotation *annotation_Dest = [[MAPointAnnotation alloc] init];
                annotation_Dest.title = @"终点";
                annotation_Dest.coordinate = CLLocationCoordinate2DMake(self.ordersDetailsModel.destLat, self.ordersDetailsModel.destLng);
                [annotationArray addObject:annotation_Dest];
            }
            
            
            [self.mapView addAnnotations:annotationArray];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [self.mapView showAnnotations:annotationArray edgePadding:UIEdgeInsetsMake(80, 80, 230, 80) animated:YES];
            });
            
            
            
        }else if (self.orderStatusEnumCode == OrderStatusEnumCode_DriverSetOut_GoToPickUpPassengers || self.orderStatusEnumCode == OrderStatusEnumCode_PickedUpPasengers_StrokeStart) { // 行程中的订单详情
            
            MAPointAnnotation *annotation_Origin = [[MAPointAnnotation alloc] init];
            annotation_Origin.title = @"起点";
            annotation_Origin.coordinate = CLLocationCoordinate2DMake(self.ordersDetailsModel.originLat, self.ordersDetailsModel.originLng);
            NSArray *annotationArray = @[annotation_Origin];
            
            [self.mapView addAnnotations:annotationArray];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                self.mapViewToTop.constant = -190;
                [self.mapView showAnnotations:annotationArray edgePadding:UIEdgeInsetsMake(80, 80, 230, 80) animated:YES];
                [self.mapView setZoomLevel:16];
            });
            
        }else if (self.orderStatusEnumCode == OrderStatusEnumCode_PassengerOrder_WaitingForAnswer || self.orderStatusEnumCode == OrderStatusEnumCode_DriverReceivedOrder_DetermineStroke) {
            
            if ([self.ordersDetailsModel.typeTime isEqualToString:@"3"] || [self.ordersDetailsModel.typeTime isEqualToString:@"4"]) {
                
                MAPointAnnotation *annotation_Origin = [[MAPointAnnotation alloc] init];
                annotation_Origin.title = @"起点";
                annotation_Origin.coordinate = CLLocationCoordinate2DMake(self.ordersDetailsModel.originLat, self.ordersDetailsModel.originLng);
                NSArray *annotationArray = @[annotation_Origin];
                [self.mapView addAnnotations:annotationArray];
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    [self.mapView showAnnotations:annotationArray edgePadding:UIEdgeInsetsMake(80, 80, 230, 80) animated:YES];
                    [self.mapView setZoomLevel:16];
                });
            }else {
                
                [self beginRoutePlanning];
            }
        }
    }
}

#pragma mark - 开始线路规划
- (void)beginRoutePlanning {
    
    MAPointAnnotation *annotation_Origin = [[MAPointAnnotation alloc] init];
    annotation_Origin.title = @"起点";
    annotation_Origin.coordinate = CLLocationCoordinate2DMake(self.ordersDetailsModel.originLat, self.ordersDetailsModel.originLng);
    
    MAPointAnnotation *annotation_Dest = [[MAPointAnnotation alloc] init];
    annotation_Dest.title = @"终点";
    annotation_Dest.coordinate = CLLocationCoordinate2DMake(self.ordersDetailsModel.destLat, self.ordersDetailsModel.destLng);
    NSArray *annotationArray = @[annotation_Origin , annotation_Dest];
    [self.mapView addAnnotations:annotationArray];
    
    AMapDrivingRouteSearchRequest *naviRequest = [[AMapDrivingRouteSearchRequest alloc] init];
    
    naviRequest.requireExtension = YES;
    naviRequest.strategy = 0;
    
    AMapGeoPoint *orignPoint = [AMapGeoPoint locationWithLatitude:annotation_Origin.coordinate.latitude longitude:annotation_Origin.coordinate.longitude];
    naviRequest.origin = orignPoint;

    AMapGeoPoint *destPoint = [AMapGeoPoint locationWithLatitude:annotation_Dest.coordinate.latitude longitude:annotation_Dest.coordinate.longitude];
    naviRequest.destination = destPoint;
    
    if (!self.searchAPI) {
        
        self.searchAPI = [[AMapSearchAPI alloc] init];
        self.searchAPI.delegate = self;
    }
    
    [self.searchAPI AMapDrivingRouteSearch:naviRequest];
}

#pragma mark - AMapSearchDelegate
- (void)AMapSearchRequest:(id)request didFailWithError:(NSError *)error
{
    NSLog(@"路线规划失败");
}

/* 路径规划搜索回调. */
- (void)onRouteSearchDone:(AMapRouteSearchBaseRequest *)request response:(AMapRouteSearchResponse *)response
{
    if (response.route == nil)
    {
        return;
    }
    
    AMapPath *nowRoute = response.route.paths.firstObject;
    
    if (response.count > 0)
    {
        [self presentCurrentCourceWithRouteInfo:nowRoute];
    }
}

- (void)presentCurrentCourceWithRouteInfo:(AMapPath *)route {
    
    MANaviAnnotationType type = MANaviAnnotationTypeDrive;
    
    // 当前需要展示的路线
    self.naviRoute = [MANaviRoute naviRouteForPath:route withNaviType:type showTraffic:NO startPoint:[AMapGeoPoint locationWithLatitude:self.ordersDetailsModel.originLat longitude:self.ordersDetailsModel.originLng] endPoint:[AMapGeoPoint locationWithLatitude:self.ordersDetailsModel.destLat longitude:self.ordersDetailsModel.destLng]];
    
    
    self.naviRoute.routeColor = Color_3585ff; // 路线颜色
    
    
    [self.naviRoute addToMapView:self.mapView]; // 将路线添加到地图
    
    self.mapView.showsUserLocation = YES;
    self.mapView.userTrackingMode = MAUserTrackingModeFollow;
    self.mapView.showTraffic = YES;
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        [self.mapView setVisibleMapRect:[CommonUtility mapRectForOverlays:self.naviRoute.routePolylines] edgePadding:UIEdgeInsetsMake(50, 50, 250, 50) animated:YES];
    });
    
}



#pragma mark - 地图 代理 方法
static NSString *DriverIdentifier = @"Driver";
static NSString *PinIdentifier = @"Annotation";
#if MapTypeMicro == 1 // 高德地图
- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{
    
    
    if ([annotation isKindOfClass:[MAUserLocation class]])
    {
        
        MAAnnotationView *driverLocation = [mapView dequeueReusableAnnotationViewWithIdentifier:DriverIdentifier];
        
        if (driverLocation == nil) {
            
            driverLocation = [[MAAnnotationView alloc] initWithAnnotation:annotation
                                                          reuseIdentifier:DriverIdentifier];
        }
        
        driverLocation.image = [UIImage imageNamed:@""];
        
        return driverLocation;
    }
    

    if ([annotation isKindOfClass:[MAPointAnnotation class]])
    {
        
        MAAnnotationView *poiAnnotationView = (MAAnnotationView*)[self.mapView dequeueReusableAnnotationViewWithIdentifier:PinIdentifier];
        if (poiAnnotationView == nil)
        {
            poiAnnotationView = [[MAAnnotationView alloc] initWithAnnotation:annotation
                                                             reuseIdentifier:PinIdentifier];
        }
        
        poiAnnotationView.canShowCallout = YES;
        
        if ([[annotation title] isEqualToString:@"起点"]) {
            
            poiAnnotationView.image = [QXDriverConfiguration imageWithName:@"public_pic_qidian"];
            
        }else if([[annotation title] isEqualToString:@"终点"])
        {
            
            poiAnnotationView.image = [QXDriverConfiguration imageWithName:@"public_pic_zhongdian"];
        }
        
        return poiAnnotationView;
    }
    
    return nil;
}
#elif MapTypeMicro == 2 // MapBox 地图

- (MGLAnnotationView *)mapView:(MGLMapView *)mapView viewForAnnotation:(id<MGLAnnotation>)annotation {
    
    
    if ([annotation isKindOfClass:[MGLUserLocation class]]) {
        
        MGLUserLocationAnnotationView *userAnnotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:DriverIdentifier];
        
        if (userAnnotationView == nil) {
            
            userAnnotationView = [[MGLUserLocationAnnotationView alloc] initWithReuseIdentifier:DriverIdentifier];
            UIImageView *userImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
            [userAnnotationView addSubview:userImageView];
            userImageView.image = [CarImageManager getCarImage];
            userImageView.layer.cornerRadius = userImageView.frame.size.height / 2.0;
            userImageView.layer.masksToBounds = YES;
            userImageView.backgroundColor = [UIColor clearColor];
            userImageView.contentMode = UIViewContentModeCenter;
        }
        
        return userAnnotationView;
    }
    
    
    
    if ([annotation isKindOfClass:[CustomMGLPointAnnotation class]]) {
        
        CustomMGLAnnotationView *annotationView = (CustomMGLAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:PinIdentifier];
        
        if (annotationView == nil) {
            
            annotationView = [[CustomMGLAnnotationView alloc] initWithReuseIdentifier:PinIdentifier];
            annotationView.frame = CGRectMake(0, 0, 30, 30);
        }
        
        CustomMGLPointAnnotation *customPointAnnotation = (CustomMGLPointAnnotation *)annotation;
        
        if (customPointAnnotation != nil) {
            
            annotationView.backgroundColor = [UIColor clearColor];
            if ([customPointAnnotation.identifier isEqualToString:@"起点"]) {
                
                annotationView.imageView.image = [QXDriverConfiguration imageWithName:@"public_pic_qidian"];
                
            }else if ([customPointAnnotation.identifier isEqualToString:@"终点"]) {
                
                annotationView.imageView.image = [QXDriverConfiguration imageWithName:@"public_pic_zhongdian"];
            }
        }
        
        return annotationView;
    }
    
    return nil;
}

#endif



- (MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id<MAOverlay>)overlay
{
    if ([overlay isKindOfClass:[LineDashPolyline class]])
    {
        MAPolylineRenderer *polylineRenderer = [[MAPolylineRenderer alloc] initWithPolyline:((LineDashPolyline *)overlay).polyline];
        polylineRenderer.lineWidth   = 8;
        polylineRenderer.lineDash = YES;
        polylineRenderer.lineCapType = kMALineCapRound;
        polylineRenderer.lineJoinType = kMALineJoinRound;
        polylineRenderer.strokeColor = [UIColor redColor];
        
        return polylineRenderer;
    }
    if ([overlay isKindOfClass:[MANaviPolyline class]])
    {
        MANaviPolyline *naviPolyline = (MANaviPolyline *)overlay;
        MAPolylineRenderer *polylineRenderer = [[MAPolylineRenderer alloc] initWithPolyline:naviPolyline.polyline];
        
        polylineRenderer.lineWidth = 8;
        polylineRenderer.lineCapType = kMALineCapRound;
        polylineRenderer.lineJoinType = kMALineJoinRound;
        if (naviPolyline.type == MANaviAnnotationTypeWalking)
        {
            polylineRenderer.strokeColor = self.naviRoute.walkingColor;
        }
        else if (naviPolyline.type == MANaviAnnotationTypeRailway)
        {
            polylineRenderer.strokeColor = self.naviRoute.railwayColor;
        }
        else
        {
            polylineRenderer.strokeColor = self.naviRoute.routeColor;
        }
        
        return polylineRenderer;
    }
    if ([overlay isKindOfClass:[MAMultiPolyline class]])
    {
        MAMultiColoredPolylineRenderer * polylineRenderer = [[MAMultiColoredPolylineRenderer alloc] initWithMultiPolyline:overlay];
        
        polylineRenderer.lineWidth = 10;
        polylineRenderer.strokeColors = [self.naviRoute.multiPolylineColors copy];
        polylineRenderer.gradient = YES;
        polylineRenderer.lineCapType = kMALineCapRound;
        polylineRenderer.lineJoinType = kMALineJoinRound;
        return polylineRenderer;
    }
    
    return nil;
}

#pragma mark - 配置默认属性
- (void)configureDefaultsAttributes {
    
    // 更改导航条字体颜色大小
    [self.navigationController.navigationBar setTitleTextAttributes:
     @{NSFontAttributeName:[UIFont systemFontOfSize:17],
       NSForegroundColorAttributeName:[UIColor whiteColor]
       }];
    
    self.backView.layer.cornerRadius = 2.0;
    self.backView.layer.masksToBounds = YES;
    
    self.startImageView.layer.cornerRadius = 2.5;
    self.startImageView.layer.masksToBounds = YES;
    
    self.endImageView.layer.cornerRadius = 2.5;
    self.endImageView.layer.masksToBounds = YES;
    
    self.heardImageView.layer.cornerRadius = 23;
    self.heardImageView.layer.masksToBounds = YES;
    
    if (![self.userPassengerModel.face isKindOfClass:[NSNull class]] && self.userPassengerModel.face.length > 0) { // 如果值非空,并且长度大于0
        
        NSURL *url = [NSURL URLWithString:self.userPassengerModel.face];
        [self.heardImageView sd_setImageWithURL:url placeholderImage:[QXDriverConfiguration imageWithName:@"tongyong_chencheren_icon"]];
    }else {
        
        self.heardImageView.image = [QXDriverConfiguration imageWithName:@"tongyong_chencheren_icon"];
    }
    
    
    self.statusLabel.layer.cornerRadius = 4.0;
    self.statusLabel.layer.masksToBounds = YES;
    self.statusLabel.layer.borderWidth = 0.5;
    self.statusLabel.layer.borderColor = [UIColor colorWithRed:158 / 255.0 green:167 / 255.0 blue:177 / 255.0 alpha:1.0].CGColor;
    
    self.pickUpPassengerButton.layer.cornerRadius = 5.0;
    self.pickUpPassengerButton.layer.masksToBounds = YES;

    self.isReceivedTheNotificationThatPassengerHasCancelTheOrder = NO;
    
    // 初始化订单状态
    self.orderStatusEnumCode = self.ordersDetailsModel.subStatus;
    
    if (self.orderStatusEnumCode == OrderStatusEnumCode_DriverReceivedOrder_DetermineStroke) { // 200
        
        QXYYUserDriverModel *driverModel = [QXYYUserDriverModel QXYY_unarchiveObject];
        if (driverModel.type == 5 || driverModel.type == 6 || driverModel.type == 7) {
            
            [self.pickUpPassengerButton setTitle:@"出发去接货" forState:(UIControlStateNormal)];
        }else {
            
            [self.pickUpPassengerButton setTitle:@"出发去接乘客" forState:(UIControlStateNormal)];
        }
        
        
    }
    else{
        
        [self.pickUpPassengerButton setTitle:@"继续行程" forState:(UIControlStateNormal)];
    }
    
    
    
    // 配置图片
    self.leftBarButtonItem.image = [QXDriverConfiguration imageWithName:@"nav_icon_back_white"];
    [self.callPhoneButton setImage:[QXDriverConfiguration imageWithName:@"public_call"] forState:UIControlStateNormal];
    self.timeImageView.image = [QXDriverConfiguration imageWithName:@"puclic_time_gray"];
    self.aircraftImageView.image = [QXDriverConfiguration imageWithName:@"puclic_plane_gray"];
    
 
    [self userPassengerAndOrdersDetails];

    
    
}
// 获取数据
- (void)userPassengerAndOrdersDetails {
    
    // 截取
    NSString *phone = [self.userPassengerModel.mobile substringFromIndex:7];
    self.phoneTailNumberLabel.text = [NSString stringWithFormat:@"尾号%@",phone];
    // 时间
    NSTimeInterval interval = self.ordersDetailsModel.deparTime / 1000.0;
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:interval];
    NSDateFormatter *objDateformat = [[NSDateFormatter alloc] init];
    [objDateformat setDateFormat:@"MM月dd日 HH:mm"];
    self.timeLabel.text  = [objDateformat stringFromDate: date];
    
    self.aircraftLabel.hidden = YES;
    self.aircraftImageView.hidden = YES;
    /// 订单类型（行程）：1 出租车；2 专车； 3 拼车； 4 接机；5 日租/半日租
    if (self.ordersDetailsModel.typeTrip.integerValue == 1) {
        self.statusLabel.text = @"出租车    ";
        self.statusLabel.hidden = YES;
        self.backViewHeight.constant = 205;
        self.marginToDividingLine.constant = -15;
    }else if (self.ordersDetailsModel.typeTrip.integerValue == 2) {
        self.statusLabel.text = @"专车    ";
        self.statusLabel.hidden = YES;
        self.backViewHeight.constant = 205;
        self.marginToDividingLine.constant = -15;
    }else if (self.ordersDetailsModel.typeTrip.integerValue == 3) {
        self.statusLabel.text = @"拼车    ";
        self.statusLabel.hidden = YES;
        self.backViewHeight.constant = 205;
        self.marginToDividingLine.constant = -15;
    }else if (self.ordersDetailsModel.typeTrip.integerValue == 4) {
        self.statusLabel.text = @"快车    ";
        self.statusLabel.hidden = YES;
        self.backViewHeight.constant = 205;
        self.marginToDividingLine.constant = -15;
    }
    else if (self.ordersDetailsModel.typeTrip.integerValue == 5) { // 货的
        
        self.statusLabel.text = @"货的    ";
        self.statusLabel.hidden = YES;
        self.backViewHeight.constant = 205;
        self.marginToDividingLine.constant = -15;
    }else if (self.ordersDetailsModel.typeTrip.integerValue == 6) { // 骑手
        
        self.statusLabel.text = @"骑手    ";
        self.statusLabel.hidden = YES;
        self.backViewHeight.constant = 205;
        self.marginToDividingLine.constant = -15;
    }else if (self.ordersDetailsModel.typeTrip.integerValue == 7) { // 搬家
        
        self.statusLabel.text = @"搬家    ";
        self.statusLabel.hidden = YES;
        self.backViewHeight.constant = 205;
        self.marginToDividingLine.constant = -15;
    }
    
    
    if ([self.ordersDetailsModel.typeTime isEqualToString:@"3"] || [self.ordersDetailsModel.typeTime isEqualToString:@"4"]) {
        
        self.statusLabel.hidden = NO;
        self.statusLabel.text = @"包车    ";
        
        self.mapViewToTop.constant = -280;
    }
    
    
    
    // 订单状态
    switch (self.ordersDetailsModel.subStatus) {
        case 200: {
            
            self.typeLabel.text = @"未开始";
            self.infoBackViewMarignToBottom.constant = 0.0;
            break;
        }
        case 210:
        case 220:
        case 300:
        case 400: {
            
            self.typeLabel.text = @"进行中";
            self.infoBackViewMarignToBottom.constant = 0.0;
            break;
        }
        case 500:
        case 510:
        case 520: {
            
            self.typeLabel.text = @"未支付";
            self.infoBackViewMarignToBottom.constant = 0.0;
            break;
        }
        case 600:
        case 610: {
            
            self.typeLabel.text = @"已支付";
            self.infoBackViewMarignToBottom.constant = 0.0;
            break;
        }
        case OrderStatusCode_NewStroke_PassengerCancel: // 900：［新行程］乘客取消
        case OrderStatusCode_PassengersCancel_StrokeDetemination_DriverNotArrive: // 901: 乘客取消（行程确定后、司机未到达
        case OrderStatusCode_PassengersCancel_StrokeDetemination_DriverArrived: // 902: 乘客取消（行程确定后、司机到达）
        case OrderStatusCode_NewStroke_DriverCancel: // 910：［新行程］司机取消
        case OrderStatusCode_NoFare_StrokeDetermination_PassengersCancelOrder: // 90200：［无费用］［行程确定］乘客取消订单
        case OrderStatusCode_NoFare_GotoPickUpPassengers_PassengersCancelOrder: // 90210：［无费用］［去接乘客］乘客取消订单
        case OrderStatusCode_NoFare_WaitingForPassengers_PassengersCancelOrder: // 90220：［无费用］［等待乘客］乘客取消订单
        case OrderStatusCode_NoFare_StrokeDetermination_DriverCancelOrder: // 91200：［无费用］［行程确定］司机取消订单
        case OrderStatusCode_NoFare_GotoPickUpPassengers_DriverCancelOrder: // 91210：［无费用］［去接乘客］司机取消订单
        case OrderStatusCode_NoFare_WaitingForPassengers_DriverCancelOrder: // 91220：［无费用］［等待乘客］司机取消订单
        case OrderStatusCode_OrderClosedByCustomerService: // 990：客服关闭订单
        case OrderStatusCode_HaveFare_StrokeDetermination_PassengersCancelOrder: // 90511：［有费用］［行程确定］乘客取消订单
        case OrderStatusCode_HaveFare_GotoPickUpPassengers_PassengersCancelOrder: // 90512：［有费用］［去接乘客］乘客取消订单
        case OrderStatusCode_HaveFare_WaitingForPassengers_PassengersCancelOrder: // 90513：［有费用］［等待乘客］乘客取消订单
        case OrderStatusCode_HaveFare_StrokeDetermination_DriverCancelOrder: // 91521：［有费用］［行程确定］司机取消订单
        case OrderStatusCode_HaveFare_GotoPickUpPassengers_DriverCancelOrder: // 91522：［有费用］［去接乘客］司机取消订单
        case OrderStatusCode_HaveFare_WaitingForPassengers_DriverCancelOrder: // 91523：［有费用］［等待乘客］司机取消订单
        {
            
            self.typeLabel.text = @"已取消";
            self.infoBackViewMarignToBottom.constant = -65;
            break;
        }
        default: {
            
            self.typeLabel.text = @"";
            self.infoBackViewMarignToBottom.constant = 0.0;
            break;
        }
    }

    
    self.startLabel.text = self.ordersDetailsModel.originAddress;
    if ([self.ordersDetailsModel.destAddress isKindOfClass:[NSNull class]] || self.ordersDetailsModel.destAddress.length <= 0) {
        
        self.endLabel.text = @"";
    }else {
        
        self.endLabel.text = self.ordersDetailsModel.destAddress;
    }
    
}


#pragma mark -客服
- (IBAction)customerServiceAction:(UIButton *)sender {
    
//    NSString *phone = [[NSUserDefaults standardUserDefaults] valueForKey:User_KeyWord_CustomerServiceTel];
    
    NSString *phone = [QXDataManager getValueForKey:User_KeyWord_CustomerServiceTel];
    if (phone != nil) {
        
        NSString *telUrl = [NSString stringWithFormat:@"telprompt:%@",phone];
        
        NSURL *url = [[NSURL alloc] initWithString:telUrl];
        
        [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:^(BOOL success) {
            
            sender.userInteractionEnabled = YES;
        }];
        sender.userInteractionEnabled = NO;
    }
}

#pragma Action
#pragma mark -投诉
- (IBAction)complaintsAction:(id)sender {
    
    ComplaintVC *complaintVC = [ComplaintVC initComplaintVC];
    complaintVC.title = @"投诉";
    
    complaintVC.orderUuid = self.ordersDetailsModel.uuid;
    
    [self.navigationController pushViewController:complaintVC animated:YES];
}

#pragma mark -继续行程
- (IBAction)continueJourneyAction:(id)sender {
    
    
    
    if (self.ordersDetailsModel.subStatus == OrderStatusCode_DriverReceivedOrder_DetermineStroke) { // 行程为开
        
        NSString *alertTitle;
        
        AppInfoModel *appInfoModel = [[AppManager shareManager] getAppInfo];
        if (appInfoModel.AppDriverType == DriverTypeCargoTaxi || appInfoModel.AppDriverType == DriverTypeHouseMoving || appInfoModel.AppDriverType == DriverTypeRider) { // 货的,搬家,骑手
            
            alertTitle = @"现在出发去接货吗？";
        }else {
            
            alertTitle = @"现在出发去接乘客吗？";
        }
        __weak typeof(self) weakSelf = self;
        self.alertVC = [UIAlertController alertControllerWithTitle:nil message:alertTitle preferredStyle:(UIAlertControllerStyleAlert)];
        [self.alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
            
            __strong typeof(self) strongSelf = weakSelf;
            strongSelf.alertVC = nil;
            
        }]];
        
        
        [self.alertVC addAction:[UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            __strong typeof(self) strongSelf = weakSelf;
            
            [strongSelf gotoPickUpPassenger];
            strongSelf.alertVC = nil;
            [[OrderClosingManager shareManager] closeNotification];
        }]];
        
        [[SendLocationManager shareManager] configureModelInfoOfHasOrderWithTwoPointDistance:0.0 totalDistace:0.0 orderUuid:self.ordersDetailsModel.uuid orderStatus:(OrderStatusEnumCode_DriverSetOut_GoToPickUpPassengers) isSendImmediately:YES];
        
        [self presentViewController:self.alertVC animated:YES completion:nil];
        
    }else { // 返回上一级页面
        
        [[OrderClosingManager shareManager] closeNotification];
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [self.navigationController popViewControllerAnimated:YES];
    }
}

/**
 进入正在进行的订单页面 , 去接乘客,到达目的地,乘客已上车,前往目的地
 Code:
 210：［去接乘客］司机出发、去接乘客
 220：［等待乘客］司机到达、等待乘客
 300：［行程开始］乘客上车、行程开始
 */
- (void)pushIntoongoingOrdersViewControllerWithOrdersDetailsModel:(QXYYOrderDetailModel *)ordersDetailsModel UserPassengerModel:(QXYYUserPassengerModel *)userPassengerModel {
    
    
    ongoingOrdersViewController *vc = [ongoingOrdersViewController shareSelf];
    vc.ordersDetailsModel = ordersDetailsModel;
    vc.userPassengerModel = userPassengerModel;
    
    dispatch_async(dispatch_get_main_queue(), ^{   // 抢到实时单后进入订单详情
        [self.navigationController pushViewController:vc animated:YES];
    });
}

#pragma mark -导航条左侧按钮 返回按钮
- (IBAction)leftBarButtonItemAction:(id)sender {
    
    [self cancelNotification];
    
    if (self.isPoPToRootVC) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [self.navigationController popToRootViewControllerAnimated:YES];
    }else {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [self.navigationController popViewControllerAnimated:YES];
    }
    
    
}

- (void)cancelNotification {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NotificationName_LongLink_OrderChanged object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NotificationName_LongLink_BackShutDownOrder object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NotificationName_LongLink_PassengerCancelOrder object:nil];
}
#pragma mark - 打电话联系乘客
- (IBAction)callPassengerAction:(UIButton *)sender {
    
    NSString *phone = self.userPassengerModel.mobile;
    if (phone != nil) {
        
        NSString *telUrl = [NSString stringWithFormat:@"telprompt:%@",phone];
        
        NSURL *url = [[NSURL alloc] initWithString:telUrl];
        
        [[UIApplication sharedApplication] openURL:url];
    }
}



#pragma mark - 去接乘客网络请求
- (void)gotoPickUpPassenger {
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        MBProgressHUD *mb = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        mb.userInteractionEnabled = NO;
    });
    
    __weak typeof(self) weakSelf = self;
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setValue:self.ordersDetailsModel.uuid forKey:@"orderUuid"];
    [DLLApiManager gotoPickUpPassengerWithParameters:parameters success:^(id data) {
        
        __strong typeof(self) strongSelf = weakSelf;
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [MBProgressHUD hideHUDForView:strongSelf.view animated:NO];
        });
        
        if (NetWork_Success) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                strongSelf.ordersDetailsModel.subStatus = OrderStatusEnumCode_DriverSetOut_GoToPickUpPassengers; // 210
                [strongSelf pushIntoongoingOrdersViewControllerWithOrdersDetailsModel:strongSelf.ordersDetailsModel UserPassengerModel:strongSelf.userPassengerModel];
            });

        }else {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                MBProgressHUD *mb = [MBProgressHUD showWithText:NetWork_Message onView:strongSelf.view hiddenDuration:2.0];
                mb.userInteractionEnabled = NO;
            });
        }
        
    } failure:^(NSError *error) {
        
        __strong typeof(self) strongSelf = weakSelf;
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [MBProgressHUD hideHUDForView:strongSelf.view animated:NO];
            MBProgressHUD *mb = [MBProgressHUD showWithText:NetWorkNotToForce onView:strongSelf.view hiddenDuration:2.0];
            mb.userInteractionEnabled = NO;
        });
    }];
}

- (void)dealloc {
    
    NSLog(@"订单详情销毁了");
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
